package com.bawei.main

import android.Manifest
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.View
import android.webkit.JavascriptInterface
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.base.BaseActivity
import com.bawei.common.dialog.AppUpdateDialog
import com.bawei.main.databinding.ActivityMainBinding
import com.bawei.net.HttpInterceptorType
import com.bawei.net.HttpManager
import com.blankj.utilcode.util.LogUtils
import com.tencent.mmkv.MMKV
import com.tencent.smtt.sdk.WebSettings
import kotlinx.coroutines.launch

@Route(path = RoutePath.PATH_MAIN_PAGE)
class MainActivity : BaseActivity<ActivityMainBinding>() {

    private lateinit var mAppUpdateDialog: AppUpdateDialog

    //需要的用户权限
    private var needUserPermission = arrayListOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.RECORD_AUDIO,
    )

    //用户拒绝的权限
    private var unGrantPermission = arrayListOf<String>()


    override fun getLayoutId(): Int = R.layout.activity_main

    override fun initView() {
        initX5WebView()
        loadX5WebView()
        showAppUpdateDialog()
    }

    /**
     * 检查是否存在新版本
     */
    private fun checkAppNewVersion(){
        //启动一个协程，获取最新版本
        lifecycleScope.launch {
            //当页面显示时处理
            lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED){
                var appCode = packageManager.getPackageInfo(packageName, 0).versionCode
                var mainValues = (HttpManager.createApiServer(MainApiServer::class.java, HttpInterceptorType.SIGN) as MainApiServer).checkAppNewVersion(appCode).getValues()
                //判断是否需要弹出更新Dialog
                if (mainValues.isMustUpdate && !mainValues.downUrl.isNullOrEmpty()){
                    showAppUpdateDialog()
                }
            }
        }
    }

    private fun showAppUpdateDialog(){
        var hasNewVersion = MMKV.defaultMMKV().decodeBool("has_new_version", true)
        mAppUpdateDialog = AppUpdateDialog(this@MainActivity)
        if (hasNewVersion){
            MMKV.defaultMMKV().encode("has_new_version", false)
            mDataBinding.wbTencent.postDelayed({
                mAppUpdateDialog.show()
            }, 2000)
        }
    }

    private fun initX5WebView(){
        mDataBinding.wbTencent.run {
            //初始化必要设置项
            settings.run {
                javaScriptEnabled = true //是否支持JS脚本
                allowFileAccess = true  //是否支持访问文件
                loadsImagesAutomatically= true //是否支持自动加载图片
                javaScriptCanOpenWindowsAutomatically= true //是否支持JS弹窗
                layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
                useWideViewPort = true //是否支持小窗口
                builtInZoomControls = false //是否显示放大缩小图标
                cacheMode = WebSettings.LOAD_NO_CACHE //设置缓存模式
                domStorageEnabled = true //是否支持Dom树存储

                setSupportMultipleWindows(false) //是否支持多窗口
                setSupportZoom(false) //是否支持页面缩放
                setAppCacheEnabled(true) //是否支持缓存
                setGeolocationEnabled(false) //是否支持定位功能
            }

            //设置客户端
            webChromeClient = X5WebViewChromeClient()
            webViewClient = X5WebViewClient()
        }
    }




    /**
     * SP与MMKV区别
     * 1.SP是Android系统提供一种K-V存储技术，主要存储基本数据类型，MMKV是腾讯微信团队开发的，属于第三方K-V存储技术
     * 2.SP采用的xml文件来存储数据的，读取采用IO操作，MMKV使用内存映射（mmap技术）读取操作的内存而非xml文件
     */
    private fun loadX5WebView() {
       var homeUrl = MMKV.defaultMMKV().decodeString("home_url", "")
        LogUtils.i("主页面URL：${homeUrl}")
        mDataBinding.wbTencent.loadUrl(homeUrl)
        mDataBinding.wbTencent.view.overScrollMode = View.OVER_SCROLL_NEVER

        //添加JS交互接口
        mDataBinding.wbTencent.addJavascriptInterface(WebViewJsInterface(), "androidinfo") //"androidinfo"是前端H5页面中JS调用的别名或者对象名称，比如：window.anroidinfo.方法

        //用户权限检验
        mDataBinding.wbTencent.postDelayed({
            autoRequestPermission()
        }, 2000)

    }

    /**
     * 申请用户授权
     */
    private fun autoRequestPermission(): Boolean {
        //SDK6.0版本以后需要手动发起用户授权
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //清理一下历史未授权的用户权限
            unGrantPermission.clear()
            //检查用户是否同意的用户权限
            needUserPermission.forEach {
                var state = checkSelfPermission(it)
                if (state == PackageManager.PERMISSION_DENIED){
                    unGrantPermission.add(it)
                }
            }

            //对于用户还没有授权的用户权限发起授权弹窗
            if (unGrantPermission.size > 0){
                requestPermissions(unGrantPermission.toTypedArray(), 100 )
                return false
            }
        }
        return true
    }


    /**
     * 获取用户授权的结果
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //判断请求来源和SDK版本
        if(requestCode == 100 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            var hasUnGranted = false
            //是否存在还没有同意的权限
            unGrantPermission.forEach {
                if (checkSelfPermission(it) == PackageManager.PERMISSION_DENIED){
                    hasUnGranted = true
                }
            }

            //给出权限提示
            if (hasUnGranted){
                var builder = AlertDialog.Builder(this@MainActivity)
                builder.setTitle("权限提示")
                builder.setMessage("没有授权，请到应用详情中设置")
                builder.setPositiveButton("去设置"){dialog, _ ->
                    dialog.dismiss()
                    hasUnGranted= false
                    //跳转到应用详情页面
                    openAppDetailPage()
                }
                builder.setNegativeButton("取消"){dialog, _ ->
                    dialog.dismiss()
                    hasUnGranted = false
                }
                //弹出提示
                builder.create().show()
            }

        }
    }


    private fun openAppDetailPage(){
        var appDetailIntent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        appDetailIntent.data = Uri.fromParts("package", packageName, null)
        this@MainActivity.startActivity(appDetailIntent)
    }


    /**
     * 跳转到对应模块
     */
    private fun jumpModuleActivity(moduleType: String) {
        //校验用户权限
        var hasAllPermission = autoRequestPermission()
        if (!hasAllPermission) {
            showToastMsg("您没有同意相关用户权限")
            return
        }

        //根据模块ID跳转到对应页面
        when (moduleType) {
            "1", "2", "3", "4", "5", "6" -> ARouter.getInstance().build(RoutePath.PATH_PROPERTY_PAGE).withString("moduleType", moduleType).navigation()
            "7", "8", "9", "10" -> ARouter.getInstance().build(RoutePath.PATH_CULTURE_PAGE).withString("moduleType", moduleType).navigation()
            "11", "12" -> ARouter.getInstance().build(RoutePath.PATH_ATTENDANCE_PAGE).withString("moduleType", moduleType).navigation()
            "13", "14", "15" -> ARouter.getInstance().build(RoutePath.PATH_AUDIT_PAGE).withString("moduleType", moduleType).navigation()
        }
    }


    /**
     * 定义JS交互接口类
     * 特别注意：方面名必须与前端开发人员协商一致，名称保持一样
     */
    inner class WebViewJsInterface{

        @JavascriptInterface //必须添加该注解
        fun androidparking(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidapply(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidvisit(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidpatrol(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidnews(id: String) = jumpModuleActivity(id)
        @JavascriptInterface
        fun androidnoticelist(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidrepair(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddrepair(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddnotice(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidnotice(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidsign(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidattendance(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidproperty(id: String) = jumpModuleActivity(id)
        @JavascriptInterface
        fun androidcheckculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidpeople(id: String) = jumpModuleActivity(id)

    }

}